﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Staticage.Util;

namespace Staticage.Core {
    class JsonSetting : FileConfiguration {
        string filePath;
        Dictionary<string, Dictionary<string, string>> settings;
        Dictionary<string, string> section;

        public JsonSetting(string filePath)
            : base(filePath) {
            settings = SerializeHelper.JsonDeSerialize<Dictionary<string, Dictionary<string, string>>>(File.ReadAllText(this.filePath));
            ValidateSettings();
            section = settings[settings.Keys.First()];
        }

        private void ValidateSettings() {
            if (settings == null) {
                settings = new Dictionary<string, Dictionary<string, string>>(){
                    { defaultSectionName,new Dictionary<string,string>() }
                };
                this.Save();
            }
        }

        public override IConfiguration Select(string section) {
            this.section = settings[section];
            return this;
        }

        public override string GetValue(string key) {
            return section.ContainsKey(key) ? section[key] : string.Empty;
        }

        public override IConfiguration SetValue(string key, object value) {
            section[key] = value.ToString();
            return this;
        }

        public override IConfiguration Save() {
            File.WriteAllText(this.filePath, SerializeHelper.JsonSerialize(this.settings), Encoding.Default);
            return this;
        }
    }
}
